package com.zlyx.easy.drools.reader;

import java.io.File;
import java.io.FileInputStream;

import com.github.javaparser.JavaParser;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.ImportDeclaration;
import com.github.javaparser.ast.body.MethodDeclaration;
import com.github.javaparser.ast.body.TypeDeclaration;
import com.github.javaparser.ast.visitor.VoidVisitorAdapter;
import com.zlyx.easy.core.reflect.ClassBody;
import com.zlyx.easy.core.reflect.ClassBuilder;
import com.zlyx.easy.core.utils.ClassUtils;

/**
 * 解析类文件工具
 *
 * @Author 赵光
 * @Desc MethodReader
 * @Date 2020年5月30日
 */
public class DroolsReader {

	/**
	 * 将java类解析为ClassBody对象
	 *
	 * @param cls  类
	 * @param name 方法名
	 * @return
	 * @throws Exception
	 */
	public static ClassBody parse(Class<?> cls) throws Exception {
		String classPath = ClassUtils.getClassPath(cls);
		ClassBody classBody = ClassBuilder.newBody(cls);
		FileInputStream in = new FileInputStream(new File(classPath));
		CompilationUnit cu = JavaParser.parse(in);
		if (cu.getTypes().size() > 0) {
			for (ImportDeclaration importDeclaration : cu.getImports()) {
				classBody.importClass(importDeclaration.toString());
			}
			TypeDeclaration<?> typeDeclaration = cu.getTypes().get(0);
			if (typeDeclaration.hasJavaDocComment()) {
				classBody.header(typeDeclaration.getJavadocComment().get().toString());
			}
			new VoidVisitorAdapter<Void>() {
				@Override
				public void visit(MethodDeclaration methodDeclaration, Void arg) {
					String methodBody = methodDeclaration.getBody().get().toString();
					methodBody = methodBody.substring(1, methodBody.length() - 1);
					classBody.method(methodDeclaration.getNameAsString(), methodBody);
				}
			}.visit(cu, null);
		}
		return classBody;
	}

}
